﻿using BZ.Core.Frm;
using NDK.Motion.Card;
using NDK.Motion.MachineManager;
using NDK.Motion.MachineResources;
using NDK.Motion.Properties;
using NDK.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace NDK.Motion.Frm
{
    public partial class Frm_DI : Form
    {
        private static log4net.ILog traceLogger = log4net.LogManager.GetLogger("Frm_DI");

        /// <summary>
        /// 是否实时监控DI状态
        /// </summary>
        public bool isMonitoring = false;
        /// <summary>
        /// 窗体关闭状态
        /// </summary>
        public bool isFrmClosed = false;
        private Frm_DI()
        {
            InitializeComponent();


            foreach (var item in MachineDataManager.Instance.DIList)
            {
                if (item.Card != null)
                {
                    if (!cb_CardID.Items.Contains(item.Card?.CardID))
                    {
                        cb_CardID.Items.Add(item.Card.CardID);
                    }
                }
            }

        }
        private static Frm_DI _instance;
        private static readonly object singletonLock = new object();
        public static Frm_DI Instance
        {
            get
            {
                if (_instance == null || _instance.IsDisposed)
                {
                    lock (singletonLock)
                    {
                        if (_instance == null || _instance.IsDisposed)
                        {
                            _instance = new Frm_DI();
                        }
                    }
                }
                return _instance;
            }
        }
        private void Frm_DI_Load(object sender, EventArgs e)
        {
            dgv_DI.DataSource = new BindingList<InputSetting>(MachineDataManager.Instance.DIList);
            isFrmClosed = false;
            backgroundWorker1.RunWorkerAsync();
        }


        private void btn_FindDI_BtnClick(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tb_Name.Text.Trim()))
            {
                dgv_DI.DataSource = new BindingList<InputSetting>(MachineDataManager.Instance.DIList.FindAll(i => i.Name.Contains(tb_Name.Text.Trim())));
                return;
            }
            if (!string.IsNullOrEmpty(cb_CardID.Text.Trim()))
            {
                dgv_DI.DataSource = new BindingList<InputSetting>(MachineDataManager.Instance.DIList.FindAll(i => i.Card.CardID.ToString() == cb_CardID.Text.Trim()));
            }
            if (string.IsNullOrEmpty(tb_Name.Text.Trim()) && string.IsNullOrEmpty(cb_CardID.Text.Trim()))
            {
                dgv_DI.DataSource = new BindingList<InputSetting>(MachineDataManager.Instance.DIList);
            }
        }

        private void ckb_Monitoring_CheckedChanged(object sender, EventArgs e)
        {
            if (ckb_Monitoring.CheckState == CheckState.Checked)
            {
                isMonitoring = true;
            }
            else
            {
                isMonitoring = false;
            }
        }
        /// <summary>
        /// 实时监控DI状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while (isFrmClosed == false)
            {
                if (isMonitoring)
                {
                    for (int rowIndex = 0; rowIndex < dgv_DI.Rows.Count; rowIndex++)
                    {
                        try
                        {
                            //DataGridView处于编辑状态时，不检查DI状态
                            if (dgv_DI.Rows[rowIndex].IsNewRow) break;
                            if (dgv_DI.Rows[rowIndex].Cells["cName"].IsInEditMode) break;
                            //获取当前行的DI
                            string cardType = dgv_DI.Rows[rowIndex].Cells["cCardType"].Value.ToString();
                            string name = dgv_DI.Rows[rowIndex].Cells["cName"].Value.ToString();
                            string port = dgv_DI.Rows[rowIndex].Cells["cPort"].Value.ToString();
                            int cardId = int.Parse(dgv_DI.Rows[rowIndex].Cells["cCardID"].Value.ToString());

                            InputSetting inputModel = MachineDataManager.Instance.DIList.Find(i => i.Card.CardID == cardId && i.Port.ToString() == port
                            && i.Name == name && i.Card.CardType == cardType);
                            //得到DI状态，更新界面状态
                            bool diStatus = inputModel.GetStatus();
                            if (dgv_DI.Rows[rowIndex].Cells["cStatus"].Tag?.ToString().ToUpper() == diStatus.ToString().ToUpper())
                            {
                                continue;//状态没有发生变化,不设置
                            }
                            dgv_DI.Rows[rowIndex].Cells["cStatus"].Value = (diStatus == true) ? Resources.LightOn : Resources.LightOff;
                            dgv_DI.Rows[rowIndex].Cells["cStatus"].Tag = diStatus;
                        }
                        catch (Exception ex)
                        {
                            traceLogger.Error(ex.StackTrace);
                        }
                        Application.DoEvents();
                    }
                }
                Thread.Sleep(100);
                Application.DoEvents();
            }
        }

        private void dgv_DI_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void dgv_DI_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 22)
            {
                DataGridViewUtils.PasteData(dgv_DI);
            }
        }

        private void btn_Delete_BtnClick(object sender, EventArgs e)
        {
            List<InputSetting> inputSettingList = new List<InputSetting>();
            var rows = dgv_DI.SelectedRows;
            if (rows.Count > 0)
            {
                foreach (DataGridViewRow row in rows)
                {
                    //获取当前行的DI
                    string cardType = row.Cells["cCardType"].Value.ToString();
                    string name = row.Cells["cName"].Value.ToString();
                    string port = row.Cells["cPort"].Value.ToString();
                    int cardId = int.Parse(row.Cells["cCardID"].Value.ToString());

                    InputSetting inputModel = MachineDataManager.Instance.DIList.Find(i => i.Card.CardID == cardId && i.Port.ToString() == port
                    && i.Name == name && i.Card.CardType == cardType);
                    inputSettingList.Add(inputModel);
                }
                List<string> names = new List<string>();
                foreach (var inputSetting in inputSettingList)
                {
                    names.Add(inputSetting.Name);
                }
                Dlg_Confirm dlg_Confirm = new Dlg_Confirm("提示", $"确定删除{string.Join(",", names)}?");
                DialogResult dialogResult = dlg_Confirm.ShowDialog(this);
                if (dialogResult == DialogResult.OK)
                {
                    foreach (var inputSetting in inputSettingList)
                    {
                        MachineDataManager.Instance.DIList.Remove(inputSetting);
                    }
                }
                dgv_DI.DataSource = new BindingList<InputSetting>(MachineDataManager.Instance.DIList);
            }
        }

        private void Frm_DI_FormClosing(object sender, FormClosingEventArgs e)
        {
            isFrmClosed = true;
        }

        private void ucBtnExt1_BtnClick(object sender, EventArgs e)
        {
            //DataTable dataTable = FileUtils.OpenCSV("D:\\软件\\左线IO.CSV");
            //for (int i = 0; i < dataTable.Rows.Count; i++)
            //{
            //    string str1 = dataTable.Rows[i][0].ToString();
            //    if (str1.Contains("A通道"))
            //        str1 = str1.Replace("A通道", "");
            //    if (str1 == "")
            //        str1 = "备用" + i.ToString();
            //    string str2 = dataTable.Rows[i][1].ToString();
            //    int str3 = Convert.ToInt32(dataTable.Rows[i][2]);
            //    ICard card = MachineDataManager.Instance.CardList[0];
            //    MachineDataManager.Instance.DIList.Add(new InputSetting(str1, card, str3));
            //    dgv_DI.DataSource = new BindingList<InputSetting>(MachineDataManager.Instance.DIList);
            //}
            try
            {
                int port = MachineDataManager.Instance.DIList.Count;
                ICard card = MachineDataManager.Instance.CardList[0];
                MachineDataManager.Instance.DIList.Add(new InputSetting($"DI{port}({card.CardID})", card, port));
                dgv_DI.DataSource = new BindingList<InputSetting>(MachineDataManager.Instance.DIList);
            }
            catch (Exception ex) { }
        }

        private void ucBtnExt2_BtnClick(object sender, EventArgs e)
        {
            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
            ofd.Filter = "文件|*.txt";
            ofd.Multiselect = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string loadFileName = ofd.FileName;
                MachineDataManager.Instance.DIList.Clear();
                string[] strings = File.ReadAllLines(loadFileName);
                ICard card = new LCT_M60();
                card.CardType = "LCT_M60";
                int index = 0;
                for (int i = 0; i < strings.Length; i++)
                {
                    index++;
                    string[] strings1 = strings[i].Split(new char[] { ':' });
                    if (strings1[0].Equals("null"))
                    {
                        continue;
                    }
                    InputSetting input = new InputSetting("M60", card, 2, 0);
                    input.ID = index;
                    input.Name = strings1[0];
                    input.ModuleName = int.Parse(strings1[1]);
                    input.Port = int.Parse(strings1[2]);
                    input.EffectiveLevel = EFFECTIVE_LEVEL_ENUM.High;
                    MachineDataManager.Instance.DIList.Add(input);
                    dgv_DI.DataSource = new BindingList<InputSetting>(MachineDataManager.Instance.DIList);
                }
            }
        }
    }
}
